package com.song.shop.kafka;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.util.Arrays;
import java.util.Properties;

/**
 * @author Song Yinghui
 * @date 2018/9/13
 * @Version 1.0
 */
public class KafkaCustomerDemo {
    private final static String TOPIC = "java_topic" ;
    private static KafkaConsumer<String ,String> customer ;

    static {
        Properties props = new Properties();
        props.put("bootstrap.servers", "111.231.232.212:9092");
        props.put("group.id", "test");
        props.put("enable.auto.commit", "true");
        //想要读取之前的数据，必须加上
        //props.put("auto.offset.reset", "earliest");
        /* 自动确认offset的时间间隔 */
        props.put("auto.commit.interval.ms", "1000");
        /*
         * 一旦consumer和kakfa集群建立连接，
         * consumer会以心跳的方式来高速集群自己还活着，
         * 如果session.timeout.ms 内心跳未到达服务器，服务器认为心跳丢失，会做rebalence
         */
        props.put("session.timeout.ms", "30000");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        customer = new KafkaConsumer<String, String>(props);
    }
    public void customer(){
        System.out.println("---------begin ----------");
        customer.subscribe(Arrays.asList(TOPIC));
        for (;;){
            ConsumerRecords<String, String> records = customer.poll(100);
            for (ConsumerRecord<String, String> record : records){
                System.out.println("----------------------------");
                System.out.println(record.toString());
                customer.commitAsync();
            }
        }
    }

    public static void main(String[] args) {
        KafkaCustomerDemo demo = new KafkaCustomerDemo();
        demo.customer();
    }
}
